package com.kanshu.ksgb.fastread.doudou.common.util;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.text.TextUtils;

/**
 * 封装downloadmanger
 * Created by wcy on 2017\5\16 0016.
 */
public class DownloadUtils {

    private Context mAppContext;
    private DownloadManager mDownloadManager;
    private volatile static DownloadUtils sInstance;
    //下载的ID
    private long downloadId;

    private DownloadUtils(Context context) {
        mAppContext = context.getApplicationContext();
        mDownloadManager = (DownloadManager) mAppContext.getSystemService(Context.DOWNLOAD_SERVICE);
    }
    public static DownloadUtils getInstance(Context context) {
        if (sInstance == null) {
            synchronized (DownloadUtils.class) {
                if (sInstance == null) {
                    sInstance = new DownloadUtils(context);
                }
            }
        }
        return sInstance;
    }

    /**
     * 下载app
     * @param url
     * @param title
     * @param description
     * @param appName
     * @return
     */
    public long download(String url, String title, String description, String appName) {
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
        request.setAllowedOverRoaming(true);
        // 下载过程和下载完成后通知栏可见
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE | DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        request.setVisibleInDownloadsUi(true);
        // 文件保存位置
        // file:///storage/emulated/0/Android/data/your-package/files/Download/appName.apk
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, appName + ".apk");
        request.setTitle(title);
        request.setDescription(description);
        try {
            downloadId = mDownloadManager.enqueue(request);
        } catch (Exception e) {
        }

        //注册广播接收者，监听下载状态
        mAppContext.registerReceiver(receiver,
                new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
        return downloadId;
    }

    /**
     * 获取下载路径
     * @param downloadId
     * @return
     */
    public String getDownloadPath(long downloadId) {
        DownloadManager.Query query = new DownloadManager.Query().setFilterById(downloadId);
        Cursor cursor = mDownloadManager.query(query);
        if (cursor != null) {
            try {
                if (cursor.moveToFirst()) {
                    return cursor.getString(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_LOCAL_URI));
                }
            } finally {
                cursor.close();
            }
        }
        return "";
    }
    /**
     * 获取文件保存的地址
     * @param downloadId
     * @return
     */
    public Uri getDownloadUri(long downloadId) {
        return mDownloadManager.getUriForDownloadedFile(downloadId);
    }

    public DownloadManager getDownloadManager() {
        return mDownloadManager;
    }

    public int getDownloadStatus(long downloadId) {
        DownloadManager.Query query = new DownloadManager.Query().setFilterById(downloadId);
        Cursor cursor = mDownloadManager.query(query);
        if (cursor != null) {
            try {
                if (cursor.moveToFirst()) {
                    return cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS));
                }
            } finally {
                cursor.close();
            }
        }
        return -1;
    }
    /**
     * 判断下载管理程序是否可用
     * @return
     */
    public boolean canDownload() {
        try {
            int state = mAppContext.getPackageManager().getApplicationEnabledSetting("com.android.providers.downloads");
            if (state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED
                    || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER
                    || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 进入 启用/禁用 下载管理程序界面
     */
    public void skipToDownloadManager() {
        String packageName = "com.android.providers.downloads";
        Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + packageName));
        mAppContext.startActivity(intent);
    }

    //广播监听下载的各个状态
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            checkStatus();
        }
    };

    //检查下载状态
    private void checkStatus() {
        DownloadManager.Query query = new DownloadManager.Query();
        //通过下载的id查找
        query.setFilterById(downloadId);
        Cursor c = mDownloadManager.query(query);
        if (c != null && c.moveToFirst()) {
            int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
            switch (status) {
                //下载暂停
                case DownloadManager.STATUS_PAUSED:
                    break;
                //下载延迟
                case DownloadManager.STATUS_PENDING:
                    break;
                //正在下载
                case DownloadManager.STATUS_RUNNING:
                    break;
                //下载完成
                case DownloadManager.STATUS_SUCCESSFUL:
                    //下载完成安装APK
                    installAPK();
                    break;
                //下载失败
                case DownloadManager.STATUS_FAILED:
                    ToastUtil.showMessage("下载失败");
                    break;
            }
        }
        if (c != null)
            c.close();
    }

    //下载到本地后执行安装
    private void installAPK() {
        Uri downloadFileUri = null;
        //获取下载文件的Uri
        try {
            downloadFileUri = mDownloadManager.getUriForDownloadedFile(downloadId);
        } catch (Exception e) {
            DownloadManager.Query query = new DownloadManager.Query().setFilterById(downloadId);
            Cursor cursor = mDownloadManager.query(query);
            if (cursor != null && cursor.moveToFirst()) {
                int fileUriIdx = cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI);
                String fileUri = cursor.getString(fileUriIdx);
                if (!TextUtils.isEmpty(fileUri)) {
                    downloadFileUri = Uri.parse(fileUri);
                }
            }
        }
        if (downloadFileUri != null) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            if(Build.VERSION.SDK_INT>=24) {
                //添加这一句表示对目标应用临时授权该Uri所代表的文件
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            }
            intent.setDataAndType(downloadFileUri, "application/vnd.android.package-archive");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            try {
                mAppContext.startActivity(intent);
            } catch (Exception e) {
                e.printStackTrace();
                try {
                    intent.setClassName("com.android.packageinstaller", "com.android.packageinstaller.PackageInstallerActivity");
                    mAppContext.startActivity(intent);
                }catch (Exception e1){
                    e1.printStackTrace();
                }
            }
            mAppContext.unregisterReceiver(receiver);
        }
    }

}
